import { _decorator, Component, BoxCollider, ITriggerEvent } from 'cc';
import { CollisionType, Direction } from '../framework/Enum';
import { PoolManager } from '../framework/PoolManager';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component {
    // 子弹速度
    @property
    public bulletSpeed = 1
    // 子弹最远射程
    @property
    public bulletRange = 50
    // 子弹方向
    @property
    public direction = Direction.MIDDLE
    // 子弹初始z坐标
    private _bulletInitZ = 0

    start() {
        this._bulletInitZ = this.node.position.z
    }

    update(deltaTime: number) {
        const pos = this.node.position
        if (this.direction === Direction.LEFT) {
            this.node.setPosition(pos.x - deltaTime * this.bulletSpeed * 0.2, pos.y, pos.z - deltaTime * this.bulletSpeed)
        } else if (this.direction === Direction.RIGHT) {
            this.node.setPosition(pos.x + deltaTime * this.bulletSpeed * 0.2, pos.y, pos.z - deltaTime * this.bulletSpeed)
        } else {
            this.node.setPosition(pos.x, pos.y, pos.z - deltaTime * this.bulletSpeed)
        }
        // 子弹超出最远射程或超出屏幕则销毁
        if (this._bulletInitZ - this.node.position.z > this.bulletRange || Math.abs(this.node.position.z) > 40 || Math.abs(this.node.position.x) > 20) PoolManager.instantiate().putNode(this.node)
    }

    onEnable() {
        // 获取到当前的碰撞组件
        const collider = this.getComponent(BoxCollider)
        // 监听碰撞事件
        collider.on('onTriggerEnter', this._onTriggerEnter, this)
    }

    onDisEnable() {
        // 获取到当前的碰撞组件
        const collider = this.getComponent(BoxCollider)
        // 取消监听碰撞事件
        collider.off('onTriggerEnter', this._onTriggerEnter, this)
    }

    // 碰撞事件
    private _onTriggerEnter(e: ITriggerEvent) {
        // 获取碰撞物分组
        const collisionGroup = e.otherCollider.getGroup()
        if (collisionGroup === CollisionType.PLAYER) {
            // 玩家飞机
            PoolManager.instantiate().putNode(this.node)
        } else {
            // 敌方飞机
            PoolManager.instantiate().putNode(this.node)
        }
    }
}

